package cn.ffcs.uec.outStaff.action;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Messagebox;

import cn.ffcs.raptornuke.plugin.common.zk.ctrl.BasePortletComposer;
import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.outStaff.action.bean.UecOutStaffTitleEditBean;
import cn.ffcs.uec.outStaff.manager.UecOutStaffManager;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.model.UecTitle;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PlatformUtil;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;

@Controller
@Scope("prototype")
public class UecOutStaffTitleEditComposer extends BasePortletComposer {

	private static final long serialVersionUID = 3086340593438520480L;
	/**
	 * 页面bean
	 */
	private UecOutStaffTitleEditBean bean = new UecOutStaffTitleEditBean();
	/**
	 * 操作类型
	 */
	private String opType;
	/**
	 * 人员信息
	 */
	private UecOutStaffInfo uecStaffInfo;

	private boolean isOutStaffEntryExt = false;

	private UecOutStaffManager uecOutStaffManager = (UecOutStaffManager) ApplicationContextUtil
			.getBean("uecOutStaffManager");
	/**
	 * 专业技术职务
	 */
	private UecTitle uecTitle;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		Components.wireVariables(comp, bean);
	}

	/**
	 * 初始化窗口
	 * 
	 * @throws ParseException
	 */
	public void onCreate$uecTitleEditWindow() throws ParseException {
		this.bindCombobox();
		this.bindBean();
		this.checkTechposttitleIsNo();
	}

	/**
	 * 查看、编辑时判断是否是无专业技术职务
	 */
	public void checkTechposttitleIsNo() {
		String index = (String) bean.getPkTechposttitle().getSelectedItem().getValue();
		// 若无专业技术职务名称，相关数据不可填
		if ("1001A1100000000006OJ".equals(index)) {
			bean.getGlbdef5().setDisabled(true);
			bean.getGlbdef1().setDisabled(true);
			bean.getGlbdef6().setDisabled(true);
			bean.getTitlerank().setDisabled(true);
			bean.getAssorg().setDisabled(true);
			bean.getTiptopFlag().setDisabled(true);
			bean.getCertifcode().setDisabled(true);
			bean.getGlbdef4().setDisabled(true);
			// 请数据
			bean.getGlbdef5().setSelectedIndex(0);
			bean.getGlbdef1().setValue(null);
			bean.getGlbdef6().setValue(null);
			bean.getTitlerank().setSelectedIndex(0);
			bean.getAssorg().setValue(null);
			bean.getTiptopFlag().setSelectedIndex(0);
			bean.getCertifcode().setValue(null);
			bean.getGlbdef4().setValue(null);
		} 
	}
	
	/**
	 * 监听--获得职称
	 */
	public void onSelect$pkTechposttitle() {
		String index = (String) bean.getPkTechposttitle().getSelectedItem().getValue();
		// 若无专业技术职务名称，相关数据不可填
		if ("1001A1100000000006OJ".equals(index)) {
			bean.getGlbdef5().setDisabled(true);
			bean.getGlbdef1().setDisabled(true);
			bean.getGlbdef6().setDisabled(true);
			bean.getTitlerank().setDisabled(true);
			bean.getAssorg().setDisabled(true);
			bean.getTiptopFlag().setDisabled(true);
			bean.getCertifcode().setDisabled(true);
			bean.getGlbdef4().setDisabled(true);
			// 请数据
			bean.getGlbdef5().setSelectedIndex(0);
			bean.getGlbdef1().setValue(null);
			bean.getGlbdef6().setValue(null);
			bean.getTitlerank().setSelectedIndex(0);
			bean.getAssorg().setValue(null);
			bean.getTiptopFlag().setSelectedIndex(0);
			bean.getCertifcode().setValue(null);
			bean.getGlbdef4().setValue(null);
		} else {
			bean.getGlbdef5().setDisabled(false);
			bean.getGlbdef1().setDisabled(false);
			bean.getGlbdef6().setDisabled(false);
			bean.getTitlerank().setDisabled(false);
			bean.getAssorg().setDisabled(false);
			bean.getTiptopFlag().setDisabled(false);
			bean.getCertifcode().setDisabled(false);
			bean.getGlbdef4().setDisabled(false);
		}
	}

	/**
	 * 绑定combobox
	 */
	private void bindCombobox() {
		// 取得资格途径glbdef5
		ListboxUtils.rendererForEdit(bean.getGlbdef5(), NodeVoUtil.getDictionaries(UecConstants.ACCESS_QUALOFICATION));
		// 职称等级titlerank
		ListboxUtils.rendererForEdit(bean.getTitlerank(), NodeVoUtil.getDictionaries(UecConstants.TITLE_RANK));
		// 职称
		ListboxUtils.rendererForEdit(bean.getPkTechposttitle(), NodeVoUtil.getDictionaries(UecConstants.TITLE_NAME));
		// 最高istop
		List<NodeVo> nodeVoIstopList = new ArrayList<NodeVo>();
		String[][] istop = { { "Y", "是" }, { "N", "否" } };
		for (int i = 0; i < istop.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(istop[i][j]);
				nodeVo.setName(istop[i][j + 1]);
			}
			nodeVoIstopList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getTiptopFlag(), nodeVoIstopList);
	}

	/**
	 * bindBean
	 * 
	 * @throws ParseException
	 */
	public void bindBean() throws ParseException {
		// 初始化时只允许先选择--获得职称-pkTechposttitle
		bean.getGlbdef5().setDisabled(true);
		bean.getGlbdef1().setDisabled(true);
		bean.getGlbdef6().setDisabled(true);
		bean.getTitlerank().setDisabled(true);
		bean.getAssorg().setDisabled(true);
		bean.getTiptopFlag().setDisabled(true);
		bean.getCertifcode().setDisabled(true);
		bean.getGlbdef4().setDisabled(true);

		isOutStaffEntryExt = (Boolean) arg.get("isOutStaffEntryExt");
		opType = (String) arg.get("opType");
		if ("add".equals(opType)) {
			this.bean.getUecTitleEditWindow().setTitle("新增专业技术职务");
			bean.getUecTitleEditDiv().setHeight("30%");
			uecStaffInfo = (UecOutStaffInfo) arg.get("uecOutStaffInfo");
		}
		if ("view".equals(opType)) {
			this.bean.getUecTitleEditWindow().setTitle("查看专业技术职务");
			uecTitle = (UecTitle) arg.get("uecTitle");
			if (null != uecTitle) {
				PubUtil.fillBeanFromPo(uecTitle, bean);
				stringTransToDate();
				bean.getButtonDiv().setVisible(false);
				PubUtil.disableComponent(bean.getUecTitleEditWindow(), true);
			}
		}
		if ("edit".equals(opType)) {
			this.bean.getUecTitleEditWindow().setTitle("编辑专业技术职务");
			bean.getUecTitleEditDiv().setHeight("30%");
			uecTitle = (UecTitle) arg.get("uecTitle");
			if (null != uecTitle) {
				PubUtil.fillBeanFromPo(uecTitle, bean);
				stringTransToDate();
			}
		}
		if ("approvalEdit".equals(opType)) {
			this.bean.getUecTitleEditWindow().setTitle("审批专业技术职务信息修改");
			bean.getUecTitleEditDiv().setHeight("30%");
			uecTitle = (UecTitle) arg.get("uecTitle");
			if (null != uecTitle) {
				PubUtil.fillBeanFromPo(uecTitle, bean);
				stringTransToDate();
			}
		}
	}

	/**
	 * 保存
	 * 
	 * @throws Exception
	 */
	public void onOk() throws Exception {
		String msg = this.checkUacStaffData();
		if (null != msg) {
			Messagebox.show(msg);
			return;
		}
		String currentName = "";
		if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			ZkUtil.showError("当前登录用户已失效，请重新登录!", "错误提示");
			return;
		} else {
			currentName = PlatformUtil.getCurrentUser().getScreenName();
		}

		if ("add".equals(opType)) {
			instantOfOutStaffTitle(currentName);
			if (!isOutStaffEntryExt) {
				startAddProcess(currentName);
			}
			// 当发起流程时 抛出事件的参数对象 uecTitle 在接收后查询不到,此时状态为1320
			Events.postEvent("onOK", this.self, uecTitle);
			this.onCancel();

		}
		if ("edit".equals(opType)) {
			PubUtil.fillPoFromBean(bean, uecTitle);
			dateTransToString();

			uecTitle.setModifier(currentName);
			uecTitle.setModifiedtime(DateUtil.getCurrenDate());

			if (!isOutStaffEntryExt) {
				// 发起流程
				if (ApprovalUtil.getActivityFlag()) {
					// 判断该人员是否在审状态，如果是在审状态不允许再次发起此流程
					boolean isOnApproval = ApprovalUtil.isOnApproval(ApprovalConstants.OUT_STAFF_TITLE_EDIT_PROC_DEF_ID,
							uecTitle.getStaffId());
					if (isOnApproval) {
						ZkUtil.showError("在审状态不允许发起！", "错误提示");
						return;
					}
					/**
					 * 数据入库 uec_trial 修改一条记录
					 */
					Long titleIdHis = uecTitle.getTitleId();

					Long outStaffId = uecTitle.getStaffId();
					uecStaffInfo = UecOutStaffInfo.newInstance();
					uecStaffInfo.setOutStaffId(outStaffId);
					uecStaffInfo = uecOutStaffManager.findUecOutStaffInfoById(uecStaffInfo);

					uecTitle.addStatusCdIS3();
					Long titleId = uecTitle.getTitleId();

					String formTheme = "盟市外包人员专业技术职务修改流程";
					String startFlowJson = "{" + "formTheme: '" + formTheme + "'," + " formContent: '专业技术修改人员:"
							+ uecStaffInfo.getPsnName() + "'," + " procDefId: '"
							+ ApprovalConstants.OUT_STAFF_TITLE_EDIT_PROC_DEF_ID + "'," + " urgent: '1',"
							+ " atiActCategoryId: '" + ApprovalConstants.MODIFICATION_CATEGORY_ID + "',"
							+ " procDefKey: '" + ApprovalUtil.OUT_STAFF_TITLE_EDIT + "'," + " formSender: '"
							+ currentName + "'," + " primaryId: '{" + "uec_out_staff_info_his:" + outStaffId
							+ ",uec_out_staff_info:" + outStaffId + ",uec_title_his:" + titleIdHis + ",uec_title:"
							+ titleId + "'}";

					String procInstId = null;
					try {
						procInstId = ApprovalUtil.startApproval(startFlowJson);
					} catch (Exception e) {
						// 流程发起失败 数据改为失效
						uecTitle.removeOnly();
						onCancel();
						ZkUtil.showError("流程发起失败！", "错误提示");
						e.printStackTrace();
					}
					if (StrUtil.isNullOrEmpty(procInstId)) {
						uecTitle.removeOnly();
						onCancel();
						ZkUtil.showError("流程发起失败！", "错误提示");
						return;
					}
					// 第一审批人如果是发起人直接到人力审批环节
					ApprovalUtil.isCurrentAssignNames(procInstId);
					ApprovalUtil.showNextAssignee(procInstId, formTheme);
				} else {
					uecTitle.updateOnly();
					Messagebox.show("更新成功！");
				}
			}
			// 当发起流程时 抛出事件的参数对象 uecTitle 在接收后查询不到！此时状态为1320
			Events.postEvent("onOK", this.self, uecTitle);
			this.onCancel();

		}
		if ("approvalEdit".equals(opType)) {
			PubUtil.fillPoFromBean(bean, uecTitle);
			dateTransToString();
			uecTitle.setModifier(currentName);
			uecTitle.setModifiedtime(DateUtil.getCurrenDate());
			uecTitle.updateOnly();
			Events.postEvent("onOK", this.self, uecTitle);
			this.onCancel();
			Messagebox.show("更新成功！");
		}
	}

	/**
	 * 添加一个UecTitle对象
	 * 
	 * @param currentName
	 */
	private void instantOfOutStaffTitle(String currentName) {
		uecTitle = UecTitle.newInstance();
		PubUtil.fillPoFromBean(bean, uecTitle);
		dateTransToString();
		uecTitle.setStaffId(uecStaffInfo.getOutStaffId());
		uecTitle.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
		uecTitle.setPkPsndoc(uecStaffInfo.getPkPsnMsg());

		uecTitle.setCreator(currentName);
		uecTitle.setCreationtime(DateUtil.getCurrenDate());
	}

	/**
	 * 添加 流程
	 * 
	 * @param currentName
	 * @throws InterruptedException
	 */
	private void startAddProcess(String currentName) throws InterruptedException {
		// 发起流程
		if (ApprovalUtil.getActivityFlag()) {
			/**
			 * 数据入库 uec_title 添加一条记录
			 */
			Long outStaffIdHis = uecStaffInfo.getOutStaffId();
			Long outStaffId = outStaffIdHis;
			uecTitle.addStatusCdIS3();
			Long titleId = uecTitle.getTitleId();

			String formTheme = "盟市外包人员专业技术职务新增流程";
			String startFlowJson = "{" + "formTheme: '" + formTheme + "'," + " formContent: '专业技术职务新增人员:"
					+ uecStaffInfo.getPsnName() + "'," + " procDefId: '"
					+ ApprovalConstants.OUT_STAFF_TITLE_ADD_PROC_DEF_ID + "'," + " urgent: '1',"
					+ " atiActCategoryId: '" + ApprovalConstants.MODIFICATION_CATEGORY_ID + "'," + " procDefKey: '"
					+ ApprovalUtil.OUT_STAFF_TITLE_ADD + "'," + " formSender: '" + currentName + "'," + " primaryId: '{"
					+ "uec_out_staff_info_his:" + outStaffIdHis + ",uec_out_staff_info:" + outStaffId + ",uec_title:"
					+ titleId + "'}";

			String procInstId = null;
			try {
				procInstId = ApprovalUtil.startApproval(startFlowJson);
			} catch (Exception e) {
				// 流程发起失败 数据改为失效
				uecTitle.removeOnly();
				onCancel();
				ZkUtil.showError("流程发起失败！", "错误提示");
				e.printStackTrace();
			}

			if (StrUtil.isNullOrEmpty(procInstId)) {
				uecTitle.removeOnly();
				onCancel();
				ZkUtil.showError("流程发起失败！", "错误提示");
				return;
			}
			// 第一审批人如果是发起人直接到人力审批环节
			ApprovalUtil.isCurrentAssignNames(procInstId);
			ApprovalUtil.showNextAssignee(procInstId, formTheme);
		} else {
			// 直接修改
			uecTitle.addOnly();
			Messagebox.show("新增成功！");
		}
	}

	/**
	 * 取消
	 */
	public void onCancel() {
		// 关闭窗口
		this.bean.getUecTitleEditWindow().onClose();
	}

	/**
	 * 检测填入的参数是否为空
	 */
	private String checkUacStaffData() {
		if (!"1001A1100000000006OJ".equals(bean.getPkTechposttitle().getSelectedItem().getValue())) {
			if (StrUtil.isNullOrEmpty(bean.getGlbdef5().getSelectedItem().getValue())) {
				return "请选择取得资格途径";
			} else if (StrUtil.isNullOrEmpty(bean.getGlbdef1().getValue())) {
				return "请填写聘任情况";
			} else if (StrUtil.isNullOrEmpty(bean.getGlbdef6().getValue())) {
				return "请填写资格审批单位";
			} else if (StrUtil.isNullOrEmpty(bean.getTitlerank().getSelectedItem().getValue())) {
				return "请选择职称等级";
			} else if (StrUtil.isNullOrEmpty(bean.getAssorg().getValue())) {
				return "请填写评定机构";
			} else if (StrUtil.isNullOrEmpty(bean.getGlbdef4().getValue())) {
				return "请选择获取职业资格时间";
			}
		}
		return null;
	}

	/**
	 * 将Date类型时间转成String类型 Date --> String 一套模型，两套标准：日期类型需要格式化
	 */
	public void dateTransToString() {
		if (!StrUtil.isNullOrEmpty(bean.getGlbdef4().getValue())) {
			// 取得资格时间
			uecTitle.setGlbdef4(DateUtil.dateToStr(bean.getGlbdef4().getValue()));
		}
	}

	/**
	 * 将String类型的时间转换成Date类型
	 * 
	 * @throws ParseException
	 */
	public void stringTransToDate() throws ParseException {
		// 时间类型转换：String --> Date
		// 取得资格时间
		if (null != uecTitle.getGlbdef4()) {
			bean.getGlbdef4().setValue(DateUtil.patternStrToDate(uecTitle.getGlbdef4()));
		}
	}

}
